package HTTP

import (
	"SQL/db"
	"logs"
	"net/http"
	"strconv"
)

type group struct {
	GroupID   string
	Nickname  string
	GroupIcon string
}

func getGroupList(w http.ResponseWriter, req *http.Request) {
	msg, code := prepare(w, req)
	var obj interface{}
	defer func() {
		writeResult(w, code, msg, obj)
	}()
	if msg != "" {
		return
	}
	userID, _ := strconv.Atoi(req.Form["userID"][0])
	pageIndex, _ := strconv.Atoi(req.Form["pageIndex"][0])
	pageSize, _ := strconv.Atoi(req.Form["pageSize"][0])
	sql := "select *from users where id= $1"
	rows, err := db.RowQuery(sql, userID)
	defer rows.Close()
	if rows.Next() == false {
		msg = "该用户不存在"
		code = errAccountNotExist
		return
	}
	sql = "select id,nickname,icon from objects,members where members.groupid =objects.id and members.userid = $1 order by id asc limit $2 offset $3 "
	offset := pageIndex * pageSize
	var args []interface{}
	args = append(args, userID, pageSize, offset)
	rows, err = db.RowQuery(sql, args...)
	defer rows.Close()
	if err != nil {
		logs.Print("GroupList Query error", err.Error())
		code = errDBQueryFailed
		msg = err.Error()
		return
	}
	groups := make([]group, 0)
	var count = 0
	for rows.Next() {
		count++
		var gid string
		var icon string
		var nickname string
		err = rows.Scan(&gid, &nickname, &icon)
		if err != nil {
			logs.Print("GroupList rows.Scan error", err.Error())
			code = errRowsScan
			msg = err.Error()
			return
		}
		tem := &group{GroupID: gid, Nickname: nickname, GroupIcon: icon}
		groups = append(groups, *tem)
	}
	if count == 0 {
		msg = "该页已经没有数据了"
		return
	}
	obj = groups
	msg = "获取群列表成功"
}
